package com.aikon.wht.designPattern.async;

/**
 * @author haitao.wang
 */
public class DefaultAsyncResult<T> implements AsyncResult {

    T val;

    Exception exception;

    int state = RUNNING;

    Object lock = new Object();


    @Override
    public void setVal(Object val) {
        System.out.println("zzz" + val);
        state = COMPLETED;
        this.val = (T) val;
        synchronized (lock) {
            lock.notifyAll();
        }
    }

    @Override
    public T getVal() {
        return this.val;
    }

    @Override
    public void setException(Exception exception) {
        state = FAILED;
        this.exception = exception;
    }

    @Override
    public boolean isCompleted() {
        return state > RUNNING;
    }

    @Override
    public void await() throws InterruptedException {

        synchronized (lock) {
            while (!isCompleted()) {
                lock.wait();
            }
        }
    }
}
